<?php
  header("Content-type:application/json");
  include("../conn/conn.php");
 
  $json=file_get_contents("php://input");
  $arr=json_decode($json,true);
  $code =$arr['code'];
  $id=$arr['id'];
  $date= date("Y-m-d H:i:s",time());
  $sql1="INSERT into grad_select(`code`,`cid`,`date`)values('$code','$id','$date')";
 
  $sql2="UPDATE grad_course set nums = nums-1 where id=$id and nums >0";
  mysqli_autocommit($link,false);//表示事务开始 --->begin；

  $b1=mysqli_query($link,$sql1); // 正确
  mysqli_query($link,$sql2); //错误
  $affect_rows= mysqli_affected_rows($link);
   
  if(!$b1||$affect_rows<=0)   //串联电路
{
    $res=array(
      'code'=>201,
      'msg'=>'选课失败'
    );
    echo json_encode($res,true);
 
    mysqli_rollback($link);//回滚
}
else
{
  $res=array(
    'code'=>200,
    'msg'=>'选课成功'
  );
  echo json_encode($res,true);
    mysqli_commit($link);//提交
}
